<?php
/**
 * Path Funktionen
 * 
 * $Rev: $
 * $Author: $
 * $Date: $
 * $Id: $
 * $URL: $
 * @author: Adrian Liechti <info@jahweh.ch>
 * @copyright: 2010-2011 Adrian Liechti, GPL3 and CC3 BY-SA
 * TODO Kommentieren!
 */

abstract class path {
	
	protected		$path;		// ../../[dir/file.ext]
	protected		$pathRoot;	// ../[..]/dir/file.ext
	protected		$ownRoot;	// True/False
	public static	$root;		// [..]/../dir/file.ext
	
	
	abstract public function init ();
	
	
	public function __construct ($path, $_dir_) {
		$this->path		= $this->normalize($path);
		$this->pathRoot	= $this->normalize($_dir_);
		
		if (strpos($this->pathRoot, self::$root->path) === false) {
			$this->ownRoot = true;
		} else {
			$this->ownRoot = false;
			$lenRoot = strlen(self::$root->path);
			$lenThis = strlen($this->pathRoot);
			
			if ($lenThis === $lenRoot) {
				$this->pathRoot = '';
			} else {
				$this->pathRoot = substr($this->pathRoot, $lenRoot);
			}
		}
		
		$this->init();
	}
	
	public function abs () {
		return ($this->ownRoot === true ? '' : self::$root) . $this->pathRoot . '/' . $this->path;
	}
	
	public function rel () {
		return $this->pathRoot . '/' . $this->path;
	}
	
	public function path () {
		return $this->path;
	}
	
	public function exists () {
		return file_exists($this->path);
	}
	
	protected function normalize ($path) {
		/**
		 * Nimm den Pfad auseinander durch Schrägstriche [/\]
		 */
		$inSegs  = preg_split('@[/\\\]+@', $path);
	
		/**
		 * Entferne die Punktverweise
		 */
		$outSegs = array();
		foreach ($inSegs as $seg) {
			if ($seg == '' || $seg == '.') {
				continue;
			}
			if ($seg == '..') {
				array_pop($outSegs);
			} else {
				array_push($outSegs, $seg);
			}
		}
		/**
		 * Gib es als String zurück
		 */
		return implode('/', $outSegs);
	}
	
	public function __toString() {
		return $this->path;
	}
	
	public static function initRoot ($rootDir) {
		// TODO sollte nur in der Path-Klasse aufgerufen werden...
		self::$root = new rootDir($rootDir);
	}
	
}
?>